﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using Corsat.Library.DataManager;

namespace Corsat.Web._2013
{
    public partial class OnlineExam : System.Web.UI.Page
    {
        public ArrayList all_question_choises
        {
            get
            {
                if (Session["all_question_choises"] != null)
                {
                   return ((ArrayList) Session["all_question_choises"]);
                }
                return new ArrayList();
            }
            set { Session["all_question_choises"] = value; }
        }
        public ArrayList answers
        {
            get
            {
                if (Session["answers"] != null)
                {
                    return ((ArrayList)Session["answers"]);
                }
                return new ArrayList();
            }
            set { Session["answers"] = value; }
        }

        public int AccountId
        {
            get
            {
                int id = 0;
                if (Session["accountId"] != null)
                {
                    int.TryParse(Session["accountId"].ToString(), out id);
                }
                return id;
            }
        }


        public int CourseId
        {
            get
            {
                if (Request.QueryString["cid"] != null && Request.QueryString["cid"] != "")
                {
                    return System.Convert.ToInt32(Request.QueryString["cid"].ToString());
                }
                return 0;
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            //if (!IsPostBack)
            //{
            if (AccountId>0)
            {
                    /*UserCourses mycourse = new UserCourses();
                    UserManagement manage = new UserManagement();
                    myuser = manage.getuser(myuser);
                    mycourse.CourseDate = DateTime.Now;
                    mycourse.UserID = myuser.UserID;*/

                    int cid = -1;
                    bool isExamAvailable = Main.CanAttendCourseId(AccountId,CourseId);
                    if (Request.QueryString["cid"] != null && Request.QueryString["cid"] != "" &&isExamAvailable)
                    {
                        cid = System.Convert.ToInt32(Request.QueryString["cid"].ToString());
                       // mycourse.Course_ID = cid;


                        if (isExamAvailable)
                        {
                            // load exam
                            loadexam(cid);
                        }
                        else
                        {
                            //error message
                            //course_lbl.Text = (string)GetLocalResourceObject("default");
                            Label results = new Label();
                           /* if (has_course && !apply_before)
                            {
                                results.Text = (string)GetLocalResourceObject("not_outcairo");
                            }
                            else if (has_course && apply_before)
                            {
                                mycourse = manage.getcoursegrade(mycourse);
                                results.Text = (string)GetLocalResourceObject("apply_before") + "<br />" + (string)GetLocalResourceObject("you_get") + " " + mycourse.Grade.ToString();
                            }
                            else
                            {
                                results.Text = (string)GetLocalResourceObject("not_incourse");
                            }*/
                            results_pnl/*.ContentTemplateContainer*/.Controls.Add(results);
                            //panel.Controls.Add(results);
                            //submit_pnl.Visible = false;
                            //results_pnl.Update();
                        }
                    }
                    else
                    {
                        //redirect to error
                        Response.Redirect("~/Profile.aspx");
                    }

                
            }
            else
            {
                Response.Redirect("~/Profile.aspx");
            }
            //}
        }

        override protected void OnInit(EventArgs e)
{
    base.OnInit(e);
}

        public void loadexam(int cid)
        {
            try
            {
                XmlDocument myexam = new XmlDocument();
                myexam.Load(Server.MapPath("~/exams/" + cid.ToString() + ".xml"));
                all_question_choises = new ArrayList();
                answers = new ArrayList();

                course_lbl.Text = myexam.SelectSingleNode("/Exam/Subject").InnerText;

                RadioButtonList choices;
                for (int i = 0; i < myexam.SelectNodes("/Exam/Part").Count; i++)
                {
                    exam_pnl/*.ContentTemplateContainer*/.Controls.Add(new LiteralControl("<hr /><span style='text-decoration:underline;font-weight:bold;font-size:medium'>" + (i + 1).ToString() + " - " + myexam.SelectNodes("/Exam/Part").Item(i).SelectSingleNode("PartHeader").InnerText + "</span><br />"));


                    //choices = new RadioButtonList { ID = string.Format("rblQuestionChoices-{0}", i) };

                    XmlNodeList questions = myexam.SelectNodes("/Exam/Part").Item(i).SelectNodes("Question");
                    for (int j = 0; j < questions.Count; j++)
                    {
                        exam_pnl/*.ContentTemplateContainer*/.Controls.Add(new LiteralControl("<b>" + (j + 1).ToString() + " - " + questions[j].SelectSingleNode("QHeader").InnerText + "</b><br />"));
                        choices = new RadioButtonList { ID = string.Format("rblQuestionChoices-{0}", all_question_choises.Count) };
                        XmlNodeList Q_Choices = questions[j].SelectNodes("Choise");

                        for (int k = 0; k < Q_Choices.Count; k++)
                        {
                            choices.Items.Add(new ListItem(Q_Choices[k].InnerText, (k + 1).ToString()));
                        }
                        exam_pnl/*.ContentTemplateContainer*/.Controls.Add(choices);
                        all_question_choises.Add(choices);

                    }

                }

                XmlNodeList Q_answers = myexam.SelectNodes("/Exam/Part/Question/Answer");

                for (int k = 0; k < Q_answers.Count; k++)
                {
                    answers.Add(Q_answers.Item(k).InnerText);
                }
                /* exam_pnl.Update();*/
            }
            catch
            {
                Response.Redirect("~/Profile.aspx");
            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            Button1.Enabled = false;
            int grade = 0;
            RadioButtonList current;
            bool Done = true;

            for (int i = 0; i < all_question_choises.Count; i++)
            {
                //current = (RadioButtonList)all_question_choises[i];
                current = (RadioButtonList)exam_pnl.FindControl(string.Format("rblQuestionChoices-{0}", i));
                if (!String.IsNullOrEmpty(current.SelectedValue))
                    continue;
                else
                {
                    Done = false;
                    break;
                }
            }

            if (Done)
            {
                for (int i = 0; i < all_question_choises.Count; i++)
                {
                    //current = (RadioButtonList)all_question_choises[i];
                    current = (RadioButtonList)exam_pnl.FindControl(string.Format("rblQuestionChoices-{0}", i));
                    if (current.SelectedValue == answers[i].ToString())
                        grade++;
                }
                //Label results = new Label();
                //results.

                float percentage = ((float)grade/all_question_choises.Count);

                percentage = (float)Math.Round(percentage, 4);
                //if (percentage >= 0.5)
                //{
                    results.Text = " لقد حصلت على " + " " + grade.ToString() + " " +" من " + " " + all_question_choises.Count.ToString();
                    //results_pnl/*.ContentTemplateContainer*/.Controls.Add(results);
                results.Visible = true;
                linkHome.Visible = true;

                //}
                //else
                //{
                //    results.Text = (string)GetLocalResourceObject("fail");
                //    exam_pnl/*.ContentTemplateContainer*/.Controls.Add(results);
                // }

                Main.UpdateAccountCourseGrade(AccountId, CourseId, (percentage*100));

                /*UserManagement manage = new UserManagement();
                UserCourses mycourse = new UserCourses();
                CorsatUser myuser = (CorsatUser)Session["CorsatUser"];
                myuser = manage.getuser(myuser);
                mycourse.UserID = myuser.UserID;
                mycourse.Course_ID = System.Convert.ToInt32(Request.QueryString["cid"].ToString());
                mycourse.CourseDate = DateTime.Now;
                mycourse.Grade = grade;

                manage.insertcoursegrade(mycourse);*/
                //results_pnl.Update();

                exam_pnl/*.ContentTemplateContainer*/.Visible = false;
                errorLabel.Visible = false;
                //exam_pnl.Update();
            }
            else
            {
                errorLabel.Text = "يجب الإجابة على جميع الإسئلة ";
                errorLabel.Visible=true;
                //results_pnl/*.ContentTemplateContainer*/.Controls.Add(results);
                Button1.Enabled = true;
                /*results_pnl.Update();*/
            }
        }
    }
}